<?php

class BackendUserController extends GxController {

    public function filters() {
        return array('rights');
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id, 'TblBackendUser'),
        ));
    }

    public function actionCreate() {
        $model = new TblBackendUser;
        $modelUserProfile = new UserProfile;
        if (isset($_POST['TblBackendUser'])) {
            $this->saveUserProfile($model, $modelUserProfile, 'create');
        }
        $this->render('create', array('model' => $model, 'modelUserProfile' => $modelUserProfile));
    }

    public function actionUpdate($id) {
        $model = $this->loadModel($id, 'TblBackendUser');
        $modelUserProfiles = UserProfile::model()->find('user_id=:user_id', array(':user_id' => $id));
        $modelUserProfile = $this->loadModel($modelUserProfiles->profile_id, 'UserProfile');
        $this->performAjaxValidation($model, 'tbl-backend-user-form');
        if (isset($_POST['TblBackendUser'])) {
            $this->saveUserProfile($model, $modelUserProfile, 'update');
        }
        $this->render('update', array(
            'model' => $model,
            'modelUserProfile' => $modelUserProfile,
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            $uploadeDir = YiiBase::getPathOfAlias('webroot') . '/../../' . getUploadDirBackend() . $id;
            $modelUserProfiles = UserProfile::model()->find('user_id=:user_id', array(':user_id' => $id));
            $modelUserProfile = $this->loadModel($modelUserProfiles->profile_id, 'UserProfile');
            if ($modelUserProfile->photo <> "" && file_exists($uploadeDir . '/profile/' . $modelUserProfile->photo) && file_exists($uploadeDir . '/profile/thumb/' . $modelUserProfile->photo) && file_exists($uploadeDir . '/profile/minithumb/' . $modelUserProfile->photo) && file_exists($uploadeDir . '/profile/432X324/' . $modelUserProfile->photo)) {
                unlink($uploadeDir . '/profile/' . $modelUserProfile->photo);
                unlink($uploadeDir . '/profile/thumb/' . $modelUserProfile->photo);
                unlink($uploadeDir . '/profile/minithumb/' . $modelUserProfile->photo);
                unlink($uploadeDir . '/profile/432X324/' . $modelUserProfile->photo);
            }
            deleteDir($uploadeDir);
            $this->loadModel($id, 'TblBackendUser')->delete();
            $modelUserProfile->deleteAll('user_id=:id', array(':id' => $id));
            if (!Yii::app()->getRequest()->getIsAjaxRequest())
                $this->redirect(array('admin'));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('TblBackendUser');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionMyAccount() {
        $userId = Yii::app()->user->id;
        $model = $this->loadModel($userId, 'TblBackendUser');
        $model->update_time = time();
        $modelUserProfiles = UserProfile::model()->find('user_id=:user_id', array(':user_id' => $userId));
        $modelUserProfile = $this->loadModel($modelUserProfiles->profile_id, 'UserProfile');
        $uploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDirBackend() . Yii::app()->user->id;
        if (!is_dir($uploadeDir)) {
            makeUploadDir("backend");
        }

        if (isset($_POST['UserProfile'])) {
            $db_logo = $modelUserProfile->photo;
            $model->setAttributes($_POST['TblBackendUser']);
            $modelUserProfile->setAttributes($_POST['UserProfile'], false);
            $modelUserProfile->setAttribute('photo', $db_logo);
            $this->performAjaxValidation(array($model, $modelUserProfile)); //pr(array($model->user, $model));
            $validate = $modelUserProfile->validate();
            $validate = $model->validate() && $validate;
            if ($validate) {
                $transaction = Yii::app()->getDb()->beginTransaction();
                try {
                    if ($model->save(false)) {
                        if (!empty($_FILES['UserProfile']['name']['photo'])) {
                            if (file_exists($uploadeDir . '/profile/' . $modelUserProfile->photo) && file_exists($uploadeDir . '/profile/thumb/' . $modelUserProfile->photo) && file_exists($uploadeDir . '/profile/minithumb/' . $modelUserProfile->photo) && file_exists($uploadeDir . '/profile/432X324/' . $modelUserProfile->photo)) {
                                unlink($uploadeDir . '/profile/' . $modelUserProfile->photo);
                                unlink($uploadeDir . '/profile/thumb/' . $modelUserProfile->photo);
                                unlink($uploadeDir . '/profile/minithumb/' . $modelUserProfile->photo);
                                unlink($uploadeDir . '/profile/432X324/' . $modelUserProfile->photo);
                            }
                            $modelUserProfile->photo = CUploadedFile::getInstance($modelUserProfile, 'photo');
                            $fileInfo = pathinfo($modelUserProfile->photo);
                            $ext = $fileInfo['extension'];
                            $image = $_FILES['UserProfile']['tmp_name'];
                            $mainTempImages = $image['photo'];
                            $rfilename = guid() . "." . strtolower($ext);
                            $uploadnewDirProfile = $uploadeDir . '/profile/' . $rfilename;
                            $uploadnewDirProfileThumb = $uploadeDir . '/profile/thumb/' . $rfilename;
                            $uploadnewDirProfileMiniThumb = $uploadeDir . '/profile/minithumb/' . $rfilename;
                            $uploadnewDirProfileMain = $uploadeDir . '/profile/432X324/' . $rfilename;

                            $modelUserProfile->photo->saveAs($uploadnewDirProfile);

                            $image = Yii::app()->image->load($uploadnewDirProfile);
                            $image->resize(USER_IMAGE_WIDTH, USER_IMAGE_HEIGHT, Image::NONE);
                            $image->save($uploadnewDirProfileThumb);

                            $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                            $imageThumb->resize(USER_IMAGE_THUMB_WIDTH, USER_IMAGE_THUMB_HEIGHT, Image::NONE);
                            $imageThumb->save($uploadnewDirProfileMiniThumb);

                            $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                            $imageThumb->resize(USER_IMAGE_PROFILE_WIDTH, USER_IMAGE_PROFILE_HEIGHT, Image::NONE);
                            $imageThumb->save($uploadnewDirProfileMain);

                            $modelUserProfile->photo = $rfilename;
                            $modelUserProfile->setAttribute('photo', $modelUserProfile->photo);
                        }


                        $save = $modelUserProfile->save(false);
                    }
                    $transaction->commit();
                    if ($save) {
                        if (Yii::app()->getRequest()->getIsAjaxRequest())
                            Yii::app()->end();
                        Yii::app()->user->setFlash('updateProfile', 'Your profile update successfully.');
                        $this->redirect(array('viewProfile'));
                    }
                } catch (Exception $e) {
                    $transaction->rollback();
                    throw $e;
                }
            }
        }

        $this->render('myAccount', array('model' => $model, 'modelUserProfile' => $modelUserProfile));
    }

    public function actionViewProfile() {
        $userId = Yii::app()->user->id;
        $model = $this->loadModel($userId, 'TblBackendUser');
        $modelUserProfiles = UserProfile::model()->find('user_id=:user_id', array(':user_id' => $userId));
        $modelUserProfile = $this->loadModel($modelUserProfiles->profile_id, 'UserProfile');

        $this->render('viewProfile', array(
            'model' => $model, 'modelUserProfile' => $modelUserProfile
        ));
    }

    public function actionChangePassword() {
        $userId = Yii::app()->user->id;
        $password = md5($_POST['password']);
        TblBackendUser::model()->updateByPk($userId, array('password' => $password));
        Yii::app()->user->setFlash('success', Yii::t("msg", "Your password change successfully!"));
        $this->redirect(array('myAccount'));
        exit();
    }

    public function actionAdmin() {
        $model = new TblBackendUser('search');
        $model->unsetAttributes();
        $statusChangeUrl = Yii::app()->createUrl('backendUser/statuschange/');
        if (isset($_GET['TblBackendUser']))
            $model->setAttributes($_GET['TblBackendUser']);

        $this->render('admin', array(
            'model' => $model,
            'statusChangeUrl' => $statusChangeUrl,
        ));
    }

    public function saveUserProfile($model, $modelUserProfile, $operation) {
        $uploadeDir = YiiBase::getPathOfAlias('webroot') . '/' . getUploadDirBackend();
        if ($operation == "create") {
            /* For new record entry */
            if (isset($_POST['UserProfile'])) {
                $db_logo = $modelUserProfile->photo;
                $model->setAttributes($_POST['TblBackendUser']);
                $modelUserProfile->setAttributes($_POST['UserProfile'], false);
                $model->setAttribute('photo', $db_logo);
                $this->performAjaxValidation(array($model, $modelUserProfile)); //pr(array($model->user, $model));
                $validate = $modelUserProfile->validate();
                $validate = $model->validate() && $validate;
                $model->setAttribute('status', $_POST['TblBackendUser']['status']);
                $model->createtime = time();
                if ($validate) {
                    if ($model->isNewRecord) {
                        $model->password = md5($model->password);
                    }
                    $transaction = Yii::app()->getDb()->beginTransaction();
                    try {
                        if ($model->save(false)) {
                            $modelUserProfile->user_id = $model->id;
                            if (!empty($_FILES['UserProfile']['name']['photo'])) {
                                $uploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDirBackend() . $modelUserProfile->user_id;
                                if (!is_dir($uploadeDir)) {
                                    makeUploadDir("backend/" . $modelUserProfile->user_id);
                                }
                                $modelUserProfile->photo = CUploadedFile::getInstance($modelUserProfile, 'photo');
                                $fileInfo = pathinfo($modelUserProfile->photo);
                                $ext = $fileInfo['extension'];
                                $image = $_FILES['UserProfile']['tmp_name'];
                                $mainTempImages = $image['photo'];
                                $rfilename = guid() . "." . strtolower($ext);

                                $uploadnewDirProfile = $uploadeDir . '/profile/' . $rfilename;
                                $uploadnewDirProfileThumb = $uploadeDir . '/profile/thumb/' . $rfilename;
                                $uploadnewDirProfileMiniThumb = $uploadeDir . '/profile/minithumb/' . $rfilename;
                                $uploadnewDirProfileMain = $uploadeDir . '/profile/432X324/' . $rfilename;

                                $modelUserProfile->photo->saveAs($uploadnewDirProfile);

                                $image = Yii::app()->image->load($uploadnewDirProfile);
                                $image->resize(USER_IMAGE_WIDTH, USER_IMAGE_HEIGHT, Image::NONE);
                                $image->save($uploadnewDirProfileThumb);

                                $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                                $imageThumb->resize(USER_IMAGE_THUMB_WIDTH, USER_IMAGE_THUMB_HEIGHT, Image::NONE);
                                $imageThumb->save($uploadnewDirProfileMiniThumb);

                                $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                                $imageThumb->resize(USER_IMAGE_PROFILE_WIDTH, USER_IMAGE_PROFILE_HEIGHT, Image::NONE);
                                $imageThumb->save($uploadnewDirProfileMain);
                                $modelUserProfile->photo = $rfilename;
                                $modelUserProfile->setAttribute('photo', $modelUserProfile->photo);
                                $modelUserProfile->setAttribute('user_id', $model->id);
                            }
                            $save = $modelUserProfile->save();
                        }
                        $transaction->commit();
                        if ($save) {

                            if (Yii::app()->getRequest()->getIsAjaxRequest())
                                Yii::app()->end();
                            else
                                $this->redirect(array('backendUser/view/' . $model->id));
                        }
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                }
            }
        } else {
            /* For update existing record */
            if (isset($_POST['UserProfile'])) {
                $db_logo = $modelUserProfile->photo;
                $model->setAttributes($_POST['TblBackendUser'], false);
                $modelUserProfile->setAttributes($_POST['UserProfile'], false);
                $model->setAttribute('photo', $db_logo);
                $this->performAjaxValidation(array($model, $modelUserProfile)); //pr(array($model->user, $model));
                $validate = $modelUserProfile->validate();
                $validate = $model->validate() && $validate;
                $model->setAttribute('status', $_POST['TblBackendUser']['status']);
                $model->update_time = time();
                if ($validate) {
                    $transaction = Yii::app()->getDb()->beginTransaction();
                    try {

                        if ($model->save(false)) {
                            $userProfile = $modelUserProfile->findByAttributes(array('user_id' => $model->id));
                            $modelUserProfile->user_id = $model->id;
                            if ($_FILES['UserProfile']['name']['photo'] <> "") {
                                $modelUserProfile->photo = CUploadedFile::getInstance($modelUserProfile, 'photo');
                                $fileInfo = pathinfo($modelUserProfile->photo);
                                $ext = $fileInfo['extension'];
                                $image = $_FILES['UserProfile']['tmp_name'];
                                $mainTempImages = $image['photo'];
                                $rfilename = guid() . "." . strtolower($ext);
                                $uploadnewDir = $uploadeDir . $rfilename;
                                if ($userProfile->photo <> "" && file_exists($uploadeDir . $userProfile->photo)) {
                                    unlink($uploadeDir . $userProfile->photo);
                                }
                                $modelUserProfile->photo->saveAs($uploadnewDir);
                                $image = Yii::app()->image->load($uploadnewDir);
                                $image->resize(USER_IMAGE_WIDTH, USER_IMAGE_HEIGHT, Image::NONE);
                                $image->save();
                                $modelUserProfile->photo = $rfilename;
                            } else {

                                $modelUserProfile->photo = $userProfile->photo;
                            }
                            $modelUserProfile->update_time = date("Y-m-d H:i:s");
                            $save = $modelUserProfile->save();
                        }
                        $transaction->commit();
                        if ($save) {

                            if (Yii::app()->getRequest()->getIsAjaxRequest())
                                Yii::app()->end();
                            else
                                $this->redirect(array('backendUser/view/' . $model->id));
                        }
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                }
            }
        }
    }

    public function actionStatuschange() {
        $model = $this->loadModel($_POST['id'], 'TblBackendUser');
        $model->status = $_POST['status'];
        $model->save();
    }

}